from bs4 import BeautifulSoup

def createBook(book, template='template.html', target=None):
    '''
    book: 字典数据，含title,alias,author,source和content列表
    content:含章节名和段落列表
    target: 目标文件名
    '''
    if target==None: target=book['title'] +'.html'
    f = open(template, 'r', encoding='utf-8')
    soup = BeautifulSoup(f)
        
    title = soup.find('title')
    h2 = soup.find('h2')
    title.string = book['title']
    h2.string = book['title']
    
    alias = soup.find('div',id='alias')
    alias.string = '别名：' + book['alias']
    author = soup.find('div',id='author')
    author.string = '作者：' + book['author']
    source = soup.find('div',id='source')
    source.string = '来源：' + book['source']
    
    mulu = soup.find('div', class_='mulu')
    for i, c in enumerate(book['content']):
        a = soup.new_tag('a', href= '#{}'.format(i+1))
        a.string = c['name']
        mulu.contents.append(a)
    
    body = soup.find('body')
    for i, c in enumerate(book['content']):
        h4 = soup.new_tag('h4') #<h4>{}</h4>'.format(c['name']))
        h4.string = c['name']
        body.contents.append(h4)
        print( h4.string )
        
        div = soup.new_tag("div") #<div class='content'></div>")
        div['class'] = 'content'
        for chap in c['chapter']:
            if chap==None: continue
            p = soup.new_tag('p')            
            p.string = chap
            div.contents.append(p)
        body.contents.append(div)
    
    f = open(target, 'w', encoding='utf-8')
    f.write( str(soup) )
    
# book = {
    # 'title': '中国通史',
    # 'alias': 'CCTV《中国通史》纪录片解说词',
    # 'author': '中央电视台',
    # 'source': 'https://www.jianshu.com/nb/43937294',
    # 'content':[
        # {
            # 'name':'第01集：中华道路',
            # 'chapter':[
                # '这是一片神奇的土地',
                # '公元前800年到公元前200年间'
            # ]
        # },
        # {
            # 'name':'第02集：中华先祖',
            # 'chapter':[
                # '梦想，人类前行的动力。',
                # '从远古到现代，从蒸汽机到互联网'
            # ]
        # }
    # ]
# }
# createBook(book)